<?php
namespace app\admin\controller;

use app\admin\model\PackModel;
use think\Db;

class Pack extends Base
{
	public function index(){
        $platform = config('platform');
		if(IS_AJAX){

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];

            if (!empty($param['pack_number'])) {
                $where['pack_number'] = $param['pack_number'];
            }

            if (!empty($param['pack_id'])) { //商品列表反查面单需要的参数
                $where['pack_id'] = $param['pack_id'];
            }

            if (!empty($param['pay_status'])) {
                $where['pay_status'] = $param['pay_status'];
            }

            if (!empty($param['platform_code'])) {
                $where['platform_code'] = $param['platform_code'];
            }

            if (!empty($param['express_number'])) {
                //获取符合条件额面单pack_id集合
                $pack_ids = Db::name('goods')->where(['express_number'=>$param['express_number']])->group('pack_id')->getField('goods_id,pack_id');
                $where['pack_id'] = ['exp',' IN ('.implode(',',  $pack_ids).')'];
            }


            if (!empty($param['pack_status'])) {
                $where['pack_status'] = $param['pack_status'];
            }else{
                $where['pack_status'] = ['neq',5];
            }

            $pack = new PackModel();
            $selectResult = $pack->getPackByWhere($where, $offset, $limit);


            $pack_status = config('PACK_STATUS');
            $pay_status = config('PAY_STATUS');

            $userInfo = Db::name('users')->getField('user_id,nickname');
            // 拼装参数
            foreach($selectResult as $key=>$vo){
                $AboutGoods = Db::name('goods')->field('express_number')->where('pack_id',$vo['pack_id'])->group('express_number')->select();
                $str = '';
                foreach ($AboutGoods as $k => $v) {
                    $str[] = $v['express_number'];
                }
                // var_dump($str);exit;
                $selectResult[$key]['express_str'] = implode('<br/>',$str);
                $selectResult[$key]['pack_number'] = $vo['pack_number']."<br/>(".$userInfo[$vo['user_id']].")";
            	$selectResult[$key]['operate'] = showOperate($this->makeButton($vo));
                // $selectResult[$key]['user_id'] = $userInfo[$vo['user_id']];
                $selectResult[$key]['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
                $selectResult[$key]['update_time'] = date('Y-m-d H:i:s', $vo['update_time']);
                $selectResult[$key]['pack_status'] = $pack_status[$vo['pack_status']];
                $selectResult[$key]['is_print'] = $vo['is_print']?'已打印':'未打印';
                $selectResult[$key]['pay_status'] = $pay_status[$vo['pay_status']];
                $selectResult[$key]['platform_code'] = $platform[$vo['platform_code']]['name'];
                
            }



            $return['total'] = $pack->getAllPack($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }
        $id = input('id/d',0);
        $row = Db::name('pack')->field('pay_status,pack_status')->where(['pack_id'=>$id])->find();
        
        $this->assign('pack_id',$id);
        $this->assign('pack_status',$row['pack_status']);
        $this->assign('pay_status',$row['pay_status']);
        $this->assign('platform',$platform);
        return $this->fetch();
    }
	

    //签收面单
    public function setSign(){
        $id = input('id/d',0);
        $info = Db::name('pack')->where(['pack_id'=>$id])->find();
        if ($info['pack_status']!=1) {
            return json(msg(0,'','必须是已确认面单才能签收'));exit;
        }
        $res = Db::name('pack')->where(['pack_id'=>$id])->update(['pack_status'=>2,'update_time'=>time()]);
        if ($res) {
            $user = Db::name('users')->field('mobile,email,email_validated')->where(['user_id'=>$info['user_id']])->find();
            //面单对应的物流编号，可能有多个
            $Express = config('Express');
            $expressArr = Db::name('goods')->field('express_code,express_number,goods_name,goods_num')->where(['pack_id'=>$id])->group('express_number')->select();
            foreach ($expressArr as $key => $value) {
                $express[] = $value['express_number'].'（'.$Express[$value['express_code']].'）';
                $goodsInfo[] = $value['goods_name'].'（数量：'.$value['goods_num'].'）';
            }
            $express = implode(',', $express);
            //绑定邮箱的用户发邮件，没绑定的发短信
            if ($user['email']&&$user['email_validated']==1) {
                send_email($user['email'],'面单签收通知--电商之家',"尊敬的用户，您面单编号为：".$info['pack_number']."（已签收），对应包裹编号有：{$express};\n 商品信息：".implode(',',$goodsInfo));
            }else{
               //发送短信
                sendSms(3,$user['mobile'],array('pack_number'=>$info['pack_number'])); 
            }
            //将未确认商品标记为已确认  不符商品不操作
            Db::name('goods')->where(['pack_id'=>$id,'status'=>0])->setField('status',1);
            
        }
        return json(msg(1,'','操作成功'));
    }  

    // 4654654-顺丰
    // public function test(){
    //     $Express = config('Express');
    //     $expressArr = Db::name('goods')->field('express_code,express_number')->where(['pack_id'=>62])->group('express_number')->select();
    //     foreach ($expressArr as $key => $value) {
    //         $express[] = $value['express_number'].'--'.$Express[$value['express_code']];
    //     }
    //     echo implode(',', $express);exit;
    // }  

    //标记已经打印
    public function setPackSatus(){
        $id = input('id/d',0);
        $info = Db::name('pack')->where(['pack_id'=>$id])->find();
        if ($info['pack_status']==0) {
            return json(msg(0,'','必须是已确认面单才能打印'));exit;
        }
        Db::name('pack')->where(['pack_id'=>$id])->update(['is_print'=>1]);
        return json(msg(1,'','操作成功'));
    }

    //标记发货
    public function setShipping(){
        $id = input('id/d',0);
        $info = Db::name('pack')->where(['pack_id'=>$id])->find();
        if ($info['pack_status']<2||$info['is_print']==0) {
            return json(msg(0,'','必须是已确认且已打印的面单才能发货'));exit;
        }
        $res = Db::name('pack')->where(['pack_id'=>$id])->update(['pack_status'=>3,'update_time'=>time()]);
        $goodsInfo = Db::name('goods')->where(['pack_id'=>$id])->select();
		foreach ($goodsInfo as $key => $value) {
			$goodsStr[] = $value['goods_name']."(数量：".$value['goods_num'].")";
		}
        if ($res) {
            $user = Db::name('users')->field('mobile,email,email_validated')->where(['user_id'=>$info['user_id']])->find();
            //发送邮件
            if ($user['email']&&$user['email_validated']==1) {
                send_email($user['email'],'面单发货通知--电商之家',"尊敬的用户，您面单编号为：".$info['pack_number']."（已发货）\n 商品信息：".implode(',',$goodsStr));
            }else{
                 //发送短信
                sendSms(4,$user['mobile'],array('pack_number'=>$info['pack_number']));
            }
            
        }
        return json(msg(1,'','操作成功'));
    }

    //编辑面单
    public function edit(){
        return $this->fetch();
    }

    //扫码设备签收
    public function scan(){
		if(IS_AJAX){
			$code = trim(input('code/s',''));
			$type = trim(input('type/d',''));
			$goodsArr = Db::name('goods')->where(['express_number'=>$code])->group('pack_id')->select();
			$sign_log = Db::name('sign_log')->where(['express_number'=>$code])->count();
			//判断面单是否存在
			if(empty($goodsArr)){
				return json(msg(0,'','系统无该包裹记录'));
			}
			if($sign_log){
				return json(msg(0,'','该包裹已签收请勿重复扫描'));
			}
			// 启动事务
			Db::startTrans();

			try{
				Db::name('goods')->where(['express_number'=>$code])->update(['status'=>1]); //确认物流包裹所有商品为已确认
				//检测商品对应的面单是否可以更新签收状态
                foreach ($goodsArr as $key => $goods) {
                    $count = Db::name('goods')->where(['pack_id'=>$goods['pack_id'],'status'=>0])->count(); //面单对应的商品状态都为1则可以签收改面单
                    if($count==0){
                        Db::name('pack')->where(['pack_id'=>$goods['pack_id'],'pay_status'=>1])->update(['pack_status'=>2]); //面单对应的产品都已经确认 则直接更新面单为已签收
                        //通知操作
                        $Express = config('Express');
                        $expressArr = Db::name('goods')->field('express_code,express_number,goods_name,goods_num')->where(['pack_id'=>$goods['pack_id']])->group('express_number')->select();
                        $express = [];
                        foreach ($expressArr as $key => $value) {
                            $express[] = $value['express_number'].'（'.$Express[$value['express_code']].'）';
                            $goodsInfo[] = $value['goods_name'].'(数量：'.$value['goods_num'].')';
                        }
                        $expressData = implode(',', $express);

                        $info = Db::name('pack')->where(['pack_id'=>$goods['pack_id']])->find();
                        $user = Db::name('users')->field('mobile,email,email_validated')->where(['user_id'=>$info['user_id']])->find();
                        if ($user['email']&&$user['email_validated']==1) {
                            send_email($user['email'],'面单签收通知--电商之家',"尊敬的用户，您面单编号为：".$info['pack_number']."（已签收），对应包裹编号有：{$expressData}；\n商品信息：".implode(',',$goodsInfo));
                        }else{
                           //发送短信
                            sendSms(3,$user['mobile'],array('pack_number'=>$info['pack_number'])); 
                        }
                    }
                }

				Db::name('sign_log')->save(['express_number'=>$code,'create_time'=>time()]);
				
				// 提交事务
				Db::commit();  
				return json(msg(1,'','签收成功'));				
			} catch (\Exception $e) {
				// 回滚事务
				Db::rollback();
				return json(msg(0,'',$e->getMessage()));
			}
			
			
		}
        return $this->fetch();
    }
	
	 //扫码发货
    public function scanSend(){
		if(IS_AJAX){
			$code = trim(input('code/s',''));
			
			$packInfo = Db::name('pack')->field('pack_id,user_id,pack_number,pack_status,is_print')->where(['pack_number'=>$code,'pay_status'=>1])->find();
			//判断面单是否存在
			if(empty($packInfo)){
				return json(msg(0,'','系统该面单'));
			}
			if($packInfo['is_print']!=1){
				return json(msg(0,'','该面单未打印暂时无法扫描发货'));
			}
			if($packInfo['pack_status']!=2){
				return json(msg(0,'','该面单未签收暂时无法扫描发货'));
			}
			if($packInfo['pack_status']==3){
				return json(msg(0,'','该面单已经扫码，请无重复扫码'));
			}
			$goodsInfo = Db::name('goods')->where(['pack_id'=>$packInfo['pack_id']])->select();
			foreach ($goodsInfo as $key => $value) {
				$goodsStr[] = $value['goods_name']."(数量：".$goods_num.")";
			}
			// 启动事务
			Db::startTrans();
			try{
				Db::name('pack')->where(['pack_id'=>$packInfo['pack_id'],'pay_status'=>1])->update(['pack_status'=>3]); //面单对应的产品都已经确认 则直接更新面单为已发货
				//通知操作
				
				$user = Db::name('users')->field('mobile,email,email_validated')->where(['user_id'=>$packInfo['user_id']])->find();
				if ($user['email']&&$user['email_validated']==1) {
					send_email($user['email'],'面单发货通知--电商之家',"尊敬的用户，您面单编号为：".$packInfo['pack_number']."（已发货）\n产品信息为：". implode(',',$goodsStr));
				}else{
				   //发送短信
					sendSms(4,$user['mobile'],array('pack_number'=>$packInfo['pack_number'])); 
				}
				
				// 提交事务
				Db::commit();  
				return json(msg(1,'','发货成功'));				
			} catch (\Exception $e) {
				// 回滚事务
		
				Db::rollback();
				return json(msg(0,'',$e->getMessage()));
			}
			
			
		}
        return $this->fetch();
    }

    //删除面单标记为作为 pack_status=5
    public function delPack()
    {
        $pack_id = input('id/d',0);
        $time = time();
        if ($pack_id<1) {
            return json(msg(1,'','参数错误'));  
        }
        Db::startTrans();
        try{

            Db::name('pack')->where(['pack_id'=>$pack_id])->update(['create_time'=>$time,'pack_status'=>5]);
            Db::name('goods')->where(['pack_id'=>$pack_id])->update(['create_time'=>$time,'status'=>3]);
             // 提交事务
            Db::commit();  
            return json(msg(1,'','删除成功'));  
        } catch(\Exception $e){
             // 回滚事务
            Db::rollback();
            return json(msg(0,'','删除失败'));  
        }
        
    }

    public function print(){
        pdf();
    }


	/**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($vo)
    {
    	$btn = [
    		'查看商品' => [
                'auth' => 'goods/index',
                'href' => url('goods/index', ['id' => $vo['pack_id']]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-search'
            ],
            '删除' => [
                'auth' => 'pack/delpack',
                'href' => "javascript:del(".$vo['pack_id'].",'".$vo['pack_file']."')",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-pencil-square-o'
            ],
            '打印面单' => [
                'auth' => 'pack/print',
                'href' => "javascript:checkPrint(".$vo['pack_id'].",'".$vo['pack_file']."')",
                'btnStyle' => 'primary',
                'icon' => 'fa fa-print'
            ]
    	];
    	$signArr = [
    		'签收' => [
                'auth' => 'pack/signing',
                'href' => "javascript:setSign(" .$vo['pack_id'].")",
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ]
    	];
    	$sendArr = [
    		'发货' => [
                'auth' => 'pack/signing',
                'href' => "javascript:setShipping(".$vo['pack_id'].")",
                'btnStyle' => 'success',
                'icon' => 'fa fa-truck'
            ]
    	];


    	if ($vo['pack_status']==1) {
    		$btn = array_merge($btn,$signArr);
    	}
    	if ($vo['pack_status']==2) {
    		$btn = array_merge($btn,$sendArr);
    	}

    	return $btn;
        
    }
}
